package com.lyl.redis.common.aop;

import cn.hutool.core.util.StrUtil;
import com.lyl.redis.common.annotation.NoRepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
public class RepeatSubmitAspect {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Around(value = "@annotation(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();

        //获取请求URL和请求参数组成key
        String requestURI = request.getRequestURI();
        StringBuilder requestParam = new StringBuilder();
        Object[] args = pjp.getArgs();
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            requestParam.append(StrUtil.toString(arg));
            if (i != args.length - 1) {
                requestParam.append("&");
            }
        }

        String redisKey = "NO_REPEAT:" + requestURI + ":" + requestParam;
        log.info("RepeatSubmit.around  请求路径 = {}, 请求参数 = {}, 防重key = {}", requestURI, requestParam, redisKey);

        if (redisTemplate.opsForValue().increment(redisKey) > 1L) {
            //防重
            throw new RuntimeException("操作太频繁了，请稍后再试！");
        }
        try {
            redisTemplate.expire(redisKey,noRepeatSubmit.lockTime(), TimeUnit.SECONDS);
            return pjp.proceed(pjp.getArgs());
        } finally {
            redisTemplate.delete(redisKey);
        }
    }

}
